package org.dochandler.esfinge.guardian.authorizer;

import org.dochandler.service.domain.Officer;
import org.dochandler.service.domain.Rank;
import org.dochandler.service.domain.annotation.CaptainsAndCommandersOnly;
import org.dochandler.service.domain.constants.Constants;
import org.dochandler.service.exception.OfficerNotDefinedException;
import org.esfinge.guardian.authorizer.Authorizer;
import org.esfinge.guardian.context.AuthorizationContext;

public class CaptainsAndCommandersOnlyAuthorizer implements Authorizer<CaptainsAndCommandersOnly> {

	@Override
	public Boolean authorize(AuthorizationContext context, CaptainsAndCommandersOnly securityAnnotation) {
		
		Officer officer = context.getSubject().get( Constants.OFFICER.val(), Officer.class );
		if (officer == null) 
			throw new OfficerNotDefinedException("An officer must be defined at the appropriate scope");
		
		boolean isMacAllowed = ( officer.getRank().ordinal() >= Rank.CAPTAIN.ordinal() );
		boolean isCommander = officer.isCommander();
		boolean isSoldier = ( officer.getRank() == Rank.SOLDIER ); 
		
		if ( (isMacAllowed || isCommander) && !isSoldier ) {
			return true;
		}
		return false;
	}

}